package com.bysc.cmsservice.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bysc.baseservice.handler.BaiYunException;
import com.bysc.cmsservice.entity.GuideArea;
import com.bysc.cmsservice.entity.GuideType;
import com.bysc.cmsservice.entity.vo.GuideAreaQueryVo;
import com.bysc.cmsservice.service.GuideAreaService;
import com.bysc.cmsservice.service.GuideTypeService;
import com.bysc.commonutils.ResultCode;
import com.bysc.commonutils.Results;
import com.bysc.commonutils.constant.MessageConstant;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 附近攻略 前端控制器
 * </p>
 *
 * @author kkk
 * @since 2025-03-06
 */
@RestController
@Api(tags = "附近攻略内容管理")
@RequestMapping("/cmsservice/guide-area")
@RequiredArgsConstructor
public class GuideAreaController {

    @Autowired
    private GuideAreaService guideAreaService;

    @Autowired
    private GuideTypeService guideTypeService;

    /*
     * 新增攻略内容
     * */
    @ApiOperation(value = "新增攻略内容")
    @PostMapping("/addGuideArea")
    public Results addGuideArea(@RequestBody GuideArea guideArea) {
        try {
            guideAreaService.save(guideArea);
            return Results.ok().message(MessageConstant.ADD_GUIDEAREA_SUCCESS);
        } catch (Exception e) {
            throw new BaiYunException(ResultCode.ERROR, MessageConstant.ADD_GUIDEAREA_FAIL);
        }
    }


    @ApiOperation(value = "根据id查询攻略内容")
    @PostMapping("/getGuideAreaById/{id}")
    public Results getGuideAreaById(@PathVariable String id) {
        try {
            GuideArea guideArea = guideAreaService.getById(id);
            return Results.ok().data("guideArea", guideArea).message(MessageConstant.GET_GUIDEAREA_SUCCESS);
        } catch (Exception e) {
            throw new BaiYunException(ResultCode.ERROR, MessageConstant.GET_GUIDEAREA_FAIL);
        }
    }

    @ApiOperation(value = "根据id修改攻略内容")
    @PostMapping("/updateGuideAreaById/{id}")
    public Results updateGuideAreaById(@RequestBody GuideArea guideArea) {
        try {
            guideAreaService.updateById(guideArea);
            return Results.ok().message(MessageConstant.UPDATE_GUIDEAREA_SUCCESS);
        } catch (Exception e) {
            throw new BaiYunException(ResultCode.ERROR, MessageConstant.UPDATE_GUIDEAREA_FAIL);
        }
    }

    @ApiOperation(value = "查询攻略内容")
    @PostMapping("/getAllGuideArea")
    @Transactional
    public Results getAllGuideArea(@RequestBody(required = false) GuideAreaQueryVo guideAreaQueryVo) {
        try {
            LambdaQueryWrapper<GuideArea> wrapper = new LambdaQueryWrapper<>();
            // 写入查询条件
            if (guideAreaQueryVo != null) {
                String id = guideAreaQueryVo.getId();
                if (!StringUtils.isEmpty(id)) {
                    wrapper.eq(GuideArea::getId, id);
                }
                String typeId = guideAreaQueryVo.getTypeId();
                if (!StringUtils.isEmpty(typeId)) {
                    wrapper.eq(GuideArea::getTypeId, typeId);
                }
                String name = guideAreaQueryVo.getName();
                if (!StringUtils.isEmpty(name)) {
                    wrapper.like(GuideArea::getName, name);
                }
                String address = guideAreaQueryVo.getAddress();
                if(!StringUtils.isEmpty(address)){
                    wrapper.like(GuideArea::getAddress,address);
                }
                String description =guideAreaQueryVo.getDescription();
                if(!StringUtils.isEmpty(description)){
                    wrapper.like(GuideArea::getDescription,description);
                }
                String transportation = guideAreaQueryVo.getTransportation();
                if(!StringUtils.isEmpty(transportation)){
                    wrapper.like(GuideArea::getTransportation,transportation);
                }
                String openinghours = guideAreaQueryVo.getOpeninghours();
                if(!StringUtils.isEmpty(openinghours)){
                    wrapper.like(GuideArea::getOpeninghours,openinghours);
                }
            }
            List<GuideArea> guideAreas = guideAreaService.list(wrapper);
            if (guideAreas == null) {
                guideAreas = new ArrayList<>();
            }
            // 分组
            Map<String, List<GuideArea>> guideAreaMap = guideAreas.stream()
                    .collect(Collectors.groupingBy(GuideArea::getTypeId));

            // 获取 guide_type 表的 typeId 和 sort 的映射
            List<GuideType> guideTypes = guideTypeService.list(null);
            Map<String, Integer> typeIdToSortMap = guideTypes.stream()
                    .collect(Collectors.toMap(GuideType::getId, GuideType::getSort));
            // 对每个分组按 guide_type 的 sort 值排序
            List<Map.Entry<String, List<GuideArea>>> sortedEntries = new ArrayList<>(guideAreaMap.entrySet());
            sortedEntries.sort(Comparator.comparingInt(entry -> typeIdToSortMap.getOrDefault(entry.getKey(), 0)));

            // 重新构建排序后的 Map
            Map<String, List<GuideArea>> sortedGuideAreaMap = new LinkedHashMap<>();
            for (Map.Entry<String, List<GuideArea>> entry : sortedEntries) {
                sortedGuideAreaMap.put(entry.getKey(), entry.getValue());
            }

            List<Map<String, List<GuideArea>>> list = new ArrayList<>();
            list.add(sortedGuideAreaMap);

            return Results.ok()
                    .data("guideAreaMap", list)
                    .message(MessageConstant.GET_GUIDEAREA_SUCCESS);
        } catch (Exception e) {
            throw new BaiYunException(ResultCode.ERROR, MessageConstant.GET_GUIDEAREA_FAIL);
        }
    }

    private List<Map<String, List<GuideArea>>> sortmap( List<Map<String, List<GuideArea>>> list){
//        guideAreaService.list()
        return list;
    }


    /*
     * 根据id删除攻略内容
     * */
    @ApiOperation(value = "根据id删除攻略内容")
    @DeleteMapping("/deleteGuideAreaById/{id}")
    public Results deleteGuideAreaById(@PathVariable String id) {
        try {
            guideAreaService.removeById(id);
            return Results.ok().message(MessageConstant.DELETE_GUIDEAREA_SUCCESS);
        } catch (Exception e) {
            throw new BaiYunException(ResultCode.ERROR, MessageConstant.DELETE_GUIDEAREA_FAIL);
        }
    }

}

